Animation
time stamp at 1:19
Overview
Summary text here
NCL_animate_1
Please note:
Executing this script will not display a gif, but you have the option to uncomment a line at the bottom that will save a gif in the same directory as this script.
Prerequisites
Concepts |
Importance |
Notes |
|---|---|---|
Necessary |
||
Useful |
Not necessary for animations in general, but useful for the examples in this notebook |
Time to learn: X minutes
Animation Fundamentals with matplotlib
First, let’s go over some of the basics of how animation works with matplotlib.
There are two different methods of animating with matplotlib:
Function animation iteratively modifies data on a pre-existing frame to produce an animation
Artist animations pulls from a list of artists to draw in each frame to produce an animation
import cartopy.crs as ccrs
import matplotlib.animation as animation
import numpy as np
import xarray as xr
from matplotlib import pyplot as plt
import os
from PIL import Image
import geocat.datafiles as gdf
import geocat.viz as gv
Downloading file 'registry.txt' from 'https://github.com/NCAR/GeoCAT-datafiles/raw/main/registry.txt' to '/home/runner/.cache/geocat'.
Artist Animation
Before we get into those steps, let’s get some stuff to animate
Get the images into a list
First, we need to ge the images from the directory into a list. We know the only files in this directory are the images we want to plot, so let’s get get a list of all the files from that path using os.listdir().
plt.rcParams["animation.html"] = "jshtml"
dpi = 100
im_dir = "./images/goes16_hr/"
im_paths = sorted([p for p in os.listdir(im_dir) if p.endswith(".jpg")])
fig = plt.figure(figsize=tuple(t/dpi for t in Image.open(im_dir + im_paths[0]).size), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1]) # span the whole figure
ax.set_axis_off()
ims = [[ax.imshow(Image.open(im_dir + im_path), animated=True)] for im_path in im_paths]
ani = animation.ArtistAnimation(fig, ims, interval=80, blit=True, repeat_delay=1000)
ani
Function animation
Say we have some images that we want to visualize as an animation. For example, the images in the notebooks/images/goes16 directory of this repository. We can use the FuncAnimation class from matplotlib to create an animation from these images.
The steps for function animation in matplotlib are generally:
Set up all the artists that will be used in the animation and the initial frame of the animation
Create a function that updates the data in the plot to create each frame of the animation
Create a
FuncAnimationobject with the the previously created elementsSave and/or display the animation